/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package elaborate.tag_analysis.oosm.tools.mapper;

import elaborate.tag_analysis.oosm.tools.utils.SwingUtils;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author lendle
 */
public class NewProjectDialog extends javax.swing.JDialog {

    private boolean ok = false;
    private JFileChooser projectHomeFileChooser = new JFileChooser(".");
    private JFileChooser oosmFileChooser = new JFileChooser(".");
    private JFileChooser htmlFileChooser = new JFileChooser(".");

    /**
     * Creates new form NewProjectDialog
     */
    public NewProjectDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        projectHomeFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        htmlFileChooser.setFileFilter(new FileNameExtensionFilter(
                "HTML files", "html", "htm", "xhtml"));
        oosmFileChooser.setFileFilter(new FileNameExtensionFilter(
                "OOSM files", "oosm"));
        try {
            this.txProjectHome.setText(new File(".").getCanonicalPath());
        } catch (IOException ex) {
            Logger.getLogger(NewProjectDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        radioButtonGroupDocumentType = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        radioButtonHTMLFile = new javax.swing.JRadioButton();
        radioButtonURL = new javax.swing.JRadioButton();
        jSeparator1 = new javax.swing.JSeparator();
        txProjectName = new javax.swing.JTextField();
        txProjectHome = new javax.swing.JTextField();
        buttonProjectFolder = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        txProjectLocation = new javax.swing.JTextField();
        buttonOOSMFile = new javax.swing.JButton();
        txOOSMFile = new javax.swing.JTextField();
        buttonHTMLFile = new javax.swing.JButton();
        txHtmlFile = new javax.swing.JTextField();
        txURL = new javax.swing.JTextField();
        buttonCancel = new javax.swing.JButton();
        buttonOK = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

        jLabel1.setText("Project Name:");

        jLabel2.setText("Project Home Folder:");

        jLabel3.setText("OOSM File:");

        radioButtonGroupDocumentType.add(radioButtonHTMLFile);
        radioButtonHTMLFile.setSelected(true);
        radioButtonHTMLFile.setText("File:");
        radioButtonHTMLFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioButtonHTMLFileActionPerformed(evt);
            }
        });

        radioButtonGroupDocumentType.add(radioButtonURL);
        radioButtonURL.setText("URL :");
        radioButtonURL.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioButtonURLActionPerformed(evt);
            }
        });

        txProjectName.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txProjectNameKeyPressed(evt);
            }
        });

        txProjectHome.setEditable(false);

        buttonProjectFolder.setText("...");
        buttonProjectFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonProjectFolderActionPerformed(evt);
            }
        });

        jLabel4.setText("Project Location:");

        txProjectLocation.setEditable(false);

        buttonOOSMFile.setText("...");
        buttonOOSMFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonOOSMFileActionPerformed(evt);
            }
        });

        txOOSMFile.setEditable(false);

        buttonHTMLFile.setText("...");
        buttonHTMLFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonHTMLFileActionPerformed(evt);
            }
        });

        txHtmlFile.setEditable(false);

        txURL.setEditable(false);

        buttonCancel.setText("Cancel");
        buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelActionPerformed(evt);
            }
        });

        buttonOK.setText("OK");
        buttonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonOKActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(radioButtonHTMLFile)
                                .addComponent(jLabel3)
                                .addComponent(radioButtonURL))
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txProjectName)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txProjectHome)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(buttonProjectFolder))
                            .addComponent(txProjectLocation)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(txOOSMFile)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(buttonOOSMFile))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(1, 1, 1)
                                .addComponent(txHtmlFile, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(buttonHTMLFile))
                            .addComponent(txURL)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(buttonOK)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonCancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txProjectName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txProjectHome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonProjectFolder))
                .addGap(1, 1, 1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txProjectLocation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(txOOSMFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(buttonOOSMFile))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioButtonHTMLFile)
                    .addComponent(buttonHTMLFile)
                    .addComponent(txHtmlFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioButtonURL)
                    .addComponent(txURL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 6, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonCancel)
                    .addComponent(buttonOK)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
        // TODO add your handling code here:
        this.ok = false;
        this.dispose();
    }//GEN-LAST:event_buttonCancelActionPerformed

    private void buttonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOKActionPerformed
        try {
            // TODO add your handling code here:
            if (SwingUtils.isTextFieldEmpty(this.txProjectName)
                    || SwingUtils.isTextFieldEmpty(this.txProjectHome)
                    || SwingUtils.isTextFieldEmpty(this.txOOSMFile)
                    || ((SwingUtils.isTextFieldEmpty(this.txHtmlFile))
                    && (SwingUtils.isTextFieldEmpty(this.txURL)))) {
                JOptionPane.showMessageDialog(this, "Invalid value!");
                return;
            }
            this.ok = true;
            //process project folder structure
            File projectFolder = new File(this.txProjectLocation.getText());
            projectFolder.mkdirs();
            //copy files to achieve local dependencies
            ProjectConfiguration conf = this.getProjectConfiguration();
            File newOOSMFile = new File(projectFolder, conf.getOosmFile().getName());
            FileUtils.copyFile(conf.getOosmFile(), newOOSMFile);
            conf.setOosmFile(newOOSMFile);
            if (this.radioButtonHTMLFile.isSelected()) {
                File newHTMLFile = new File(projectFolder, conf.getDocumentURL().getFile().substring(conf.getDocumentURL().getFile().lastIndexOf("/")+1));
                FileUtils.copyURLToFile(conf.getDocumentURL(), newHTMLFile);
                conf.setDocumentURL(newHTMLFile.toURI().toURL());
            }

            //save project configuration
            conf.save(new File(projectFolder, "oosm.project"));
            this.dispose();
        } catch (IOException ex) {
            Logger.getLogger(NewProjectDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_buttonOKActionPerformed

    private void radioButtonHTMLFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioButtonHTMLFileActionPerformed
        // TODO add your handling code here:
        this.buttonHTMLFile.setEnabled(true);
        this.txURL.setEditable(false);
    }//GEN-LAST:event_radioButtonHTMLFileActionPerformed

    private void radioButtonURLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioButtonURLActionPerformed
        // TODO add your handling code here:
        this.buttonHTMLFile.setEnabled(false);
        this.txURL.setEditable(true);
    }//GEN-LAST:event_radioButtonURLActionPerformed

    private void buttonProjectFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonProjectFolderActionPerformed
        // TODO add your handling code here:
        if (this.projectHomeFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            this.txProjectHome.setText(this.projectHomeFileChooser.getSelectedFile().getAbsolutePath());
            if (!SwingUtils.isTextFieldEmpty(this.txProjectName)) {
                this.txProjectLocation.setText(new File(this.projectHomeFileChooser.getSelectedFile(), this.txProjectName.getText()).getAbsolutePath());
            }
        }
    }//GEN-LAST:event_buttonProjectFolderActionPerformed

    private void buttonOOSMFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOOSMFileActionPerformed
        // TODO add your handling code here:
        if (this.oosmFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            this.txOOSMFile.setText(this.oosmFileChooser.getSelectedFile().getAbsolutePath());
        }
    }//GEN-LAST:event_buttonOOSMFileActionPerformed

    private void buttonHTMLFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonHTMLFileActionPerformed
        // TODO add your handling code here:
        if (this.htmlFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            this.txHtmlFile.setText(this.htmlFileChooser.getSelectedFile().getAbsolutePath());
        }
    }//GEN-LAST:event_buttonHTMLFileActionPerformed

    private void txProjectNameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txProjectNameKeyPressed
        // TODO add your handling code here:
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                if (!SwingUtils.isTextFieldEmpty(txProjectHome)) {
                    //System.out.println(this.txProjectName.getText());
                    txProjectLocation.setText(new File(txProjectHome.getText(), txProjectName.getText()).getAbsolutePath());
                }
            }
        });

    }//GEN-LAST:event_txProjectNameKeyPressed

    public boolean isOk() {
        return ok;
    }

    public ProjectConfiguration getProjectConfiguration() throws MalformedURLException {
        ProjectConfiguration conf = new ProjectConfiguration();
        conf.setProjectName(this.txProjectName.getText());
        conf.setProjectLocation(new File(this.txProjectLocation.getText()));
        conf.setOosmFile(new File(this.txOOSMFile.getText()));
        if (this.radioButtonHTMLFile.isSelected()) {
            conf.setDocumentURL(new File(this.txHtmlFile.getText()).toURI().toURL());
        } else {
            conf.setDocumentURL(new URL(this.txURL.getText()));
        }
        return conf;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewProjectDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewProjectDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewProjectDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewProjectDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                NewProjectDialog dialog = new NewProjectDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCancel;
    private javax.swing.JButton buttonHTMLFile;
    private javax.swing.JButton buttonOK;
    private javax.swing.JButton buttonOOSMFile;
    private javax.swing.JButton buttonProjectFolder;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.ButtonGroup radioButtonGroupDocumentType;
    private javax.swing.JRadioButton radioButtonHTMLFile;
    private javax.swing.JRadioButton radioButtonURL;
    private javax.swing.JTextField txHtmlFile;
    private javax.swing.JTextField txOOSMFile;
    private javax.swing.JTextField txProjectHome;
    private javax.swing.JTextField txProjectLocation;
    private javax.swing.JTextField txProjectName;
    private javax.swing.JTextField txURL;
    // End of variables declaration//GEN-END:variables
}
